package com.zyb.patient.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.zyb.patient.R;
import com.zyb.patient.dto.CityDto;
import com.zyb.patient.dto.UserDto;
import com.zyb.patient.fragment.AboutMeFragment;
import com.zyb.patient.service.Task;
import com.zyb.patient.util.AppUtils;
import com.zyb.patient.util.Constant;
import com.zyb.patient.util.LogUtil;
import com.zyb.patient.util.Options;

/***
 * 个人资料
 * 
 * @author luoming
 */
public class AboutMeUserCenterActivity extends BaseActivity implements
		OnClickListener {

	public static final int PHOTOZOOM = 0;
	public static final int PHOTOTAKE = 1;
	public static final int IMAGE_COMPLETE = 2;
	public static final int CROPREQCODE = 3;
	public static final int UPDATE_NAME = 4;
	public static final int UPDATE_SEX = 5;
	public static final int UPDATE_CITY = 6;

	private ImageView userImg; // 用户头像
	private TextView userNameTv;// 用户姓名
	private TextView userSexTv;// 用户性别
	private TextView userPhoneTv;// 用户手机号
	private ImageView qrCodeImg;// 用户二维码头像
	private TextView userAddressTv;// 用户地区

	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private UserDto userInfo;
	private Bitmap userBmp;
	private String userSex;

	/*** 头像 ***/
	private PopupWindow popWindow;
	private LayoutInflater layoutInflater;
	private TextView photograph, albums;
	private LinearLayout cancel;
	private String photoSavePath;
	private String photoSaveName;
	private String path;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_about_me_usercenter);

		initViews();
		initUserInfo();

		initRegisterReceiver();

		overridePendingTransition(R.anim.enter_righttoleft, R.anim.noanim);

	}

	private void initViews() {
		((TextView) findViewById(R.id.head_layout_tv)).setText("个人资料");
		findViewById(R.id.head_layout_back).setOnClickListener(this);

		userImg = (ImageView) findViewById(R.id.usercenter_layout1_img);
		userNameTv = (TextView) findViewById(R.id.usercenter_layout2_tv);
		userSexTv = (TextView) findViewById(R.id.usercenter_layout3_tv);
		userPhoneTv = (TextView) findViewById(R.id.usercenter_layout4_tv);
		qrCodeImg = (ImageView) findViewById(R.id.usercenter_layout5_img);
		userAddressTv = (TextView) findViewById(R.id.usercenter_layout6_tv);

		findViewById(R.id.usercenter_layout1).setOnClickListener(this);
		findViewById(R.id.usercenter_layout2).setOnClickListener(this);
		findViewById(R.id.usercenter_layout3).setOnClickListener(this);
		// findViewById(R.id.usercenter_layout4).setOnClickListener(this);//手机
		findViewById(R.id.usercenter_layout5).setOnClickListener(this);
		findViewById(R.id.usercenter_layout6).setOnClickListener(this);

	}

	private void initUserInfo() {
		imageLoader = ImageLoader.getInstance();
		if (!imageLoader.isInited()) {
			Options.initImageLoaderConfiguration(ImageLoader.getInstance(),
					mContext);
		}
		options = Options.getListOptions();
		userInfo = getcurrentUser();
		if (userInfo != null) {
			if (!TextUtils.isEmpty(userInfo.userPic)) {
				// imageLoader.displayImage(userInfo.userPic, userImg, options);
				imageLoader.loadImage(userInfo.userPic, options,
						new SimpleImageLoadingListener() {
							public void onLoadingComplete(String imageUri,
									View view, Bitmap bmp) {
								userBmp = bmp;
								if (bmp != null) {
									userImg.setImageBitmap(AppUtils
											.toRoundCorner(userBmp, 720));
								}
							};
						});
			}

			if (!TextUtils.isEmpty(userInfo.nickname)) {
				userNameTv.setText(userInfo.nickname);
			}

			if (!TextUtils.isEmpty(userInfo.userSex)) {
				userSexTv
						.setText(userInfo.userSex.equals(Constant.SEX_MEN_KEY) ? "男"
								: "女");
			}

			if (!TextUtils.isEmpty(userInfo.phoneNumber)) {
				userPhoneTv.setText(userInfo.phoneNumber);
			}

			updateAddressTv();
		}
	}

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.head_layout_back) {
			super.onBackPressed();
		} else if (view.getId() == R.id.usercenter_layout1) {
			goUpdateUserImg();
		} else if (view.getId() == R.id.usercenter_layout2) {
			goUpdateName();
		} else if (view.getId() == R.id.usercenter_layout3) {
			goUPdateSex();
		} else if (view.getId() == R.id.usercenter_layout5) {
			goQrCode();
		} else if (view.getId() == R.id.usercenter_layout6) {
			goUpdateCity();
		}

	}

	private void goUpdateUserImg() {
		showPopupWindow(userImg);
	}

	private void goUpdateName() {
		Intent it = new Intent(mContext, UserForUpdateInfoActivity.class);
		it.putExtra("type", UserForUpdateInfoActivity.NAME_TYPE);
		it.putExtra("userName", userNameTv.getText().toString());
		// it.putExtra("userName", userInfo.nickname);
		startActivityForResult(it, UPDATE_NAME);
	}

	private void goUPdateSex() {
		Intent it = new Intent(mContext, UserForUpdateInfoActivity.class);
		it.putExtra("type", UserForUpdateInfoActivity.SEX_TYPE);
		it.putExtra(
				"sex",
				userSexTv.getText().toString().equals("男") ? Constant.SEX_MEN_KEY
						: Constant.SEX_WOMEN_KEY);
		startActivityForResult(it, UPDATE_SEX);
	}

	private void goQrCode() {
		Intent it = new Intent(mContext, UserForQrCodeActivity.class);
		startActivity(it);
	}

	private void goUpdateCity() {
		Intent it = new Intent(mContext, UserForUpdateCityActivity.class);
		it.putExtra("parentId", "1");
		startActivityForResult(it, UPDATE_CITY);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != RESULT_OK) {
			return;
		}
		Uri uri = null;
		switch (requestCode) {
		case UPDATE_NAME:// 修改用户信息成功
			if (data != null) {
				LogUtil.e("name:" + data.getStringExtra("userName"));
				if (!TextUtils.isEmpty(data.getStringExtra("userName")))
					userNameTv.setText(data.getStringExtra("userName"));
				sendBroadcast(new Intent(AboutMeFragment.COM_CHANGE_USER_INFO));
			}
			break;

		case UPDATE_SEX:// 修改用户信息成功
			if (data != null) {
				if (!TextUtils.isEmpty(data.getStringExtra("sex"))) {
					userSex = data.getStringExtra("sex");
					userSexTv
							.setText(Constant.SEX_MEN_KEY.equals(userSex) ? "男"
									: "女");
					LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
					map.put("s", "account/edit_userinfo");
					map.put("device_code", AppUtils.getmDeviceID());
					map.put("token", "token");
					map.put("sex", userSex);
					getData(map, Task.EDIT_USER_SEX, 0);
				}
			}
			break;

		case PHOTOZOOM:
			if (data == null) {
				return;
			}
			uri = data.getData();
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(uri, proj, null, null, null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			path = cursor.getString(column_index);
			Intent intent3 = new Intent(this,
					AboutMeUserCenterClipActivity.class);
			intent3.putExtra("path", path);
			startActivityForResult(intent3, IMAGE_COMPLETE);
			break;

		case PHOTOTAKE:
			path = photoSavePath + photoSaveName;
			uri = Uri.fromFile(new File(path));
			Intent intent2 = new Intent(this,
					AboutMeUserCenterClipActivity.class);
			intent2.putExtra("path", path);
			startActivityForResult(intent2, IMAGE_COMPLETE);
			break;

		case IMAGE_COMPLETE:
			final String temppath = data.getStringExtra("path");
			userImg.setImageBitmap(AppUtils.getLoacalBitmap(temppath));
			break;

		default:
			break;
		}

	}

	@SuppressWarnings("deprecation")
	private void showPopupWindow(View parent) {
		if (popWindow == null) {

			layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			File file = new File(Environment.getExternalStorageDirectory(),
					"com.zyb.patient/cache");
			if (!file.exists())
				file.mkdirs();
			photoSavePath = Environment.getExternalStorageDirectory()
					+ "/com.zyb.patient/cache/";
			photoSaveName = System.currentTimeMillis() + ".png";

			View view = layoutInflater.inflate(
					R.layout.activity_about_user_photo_pop, null);
			popWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);
			photograph = (TextView) view.findViewById(R.id.photograph);
			albums = (TextView) view.findViewById(R.id.albums);
			cancel = (LinearLayout) view.findViewById(R.id.cancel);
			photograph.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					popWindow.dismiss();
					photoSaveName = String.valueOf(System.currentTimeMillis())
							+ ".png";
					Uri imageUri = null;
					Intent openCameraIntent = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					imageUri = Uri.fromFile(new File(photoSavePath,
							photoSaveName));
					openCameraIntent.putExtra(
							MediaStore.Images.Media.ORIENTATION, 0);
					openCameraIntent
							.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
					startActivityForResult(openCameraIntent, PHOTOTAKE);
				}
			});
			albums.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					popWindow.dismiss();
					Intent openAlbumIntent = new Intent(
							Intent.ACTION_GET_CONTENT);
					openAlbumIntent.setDataAndType(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							"image/*");
					startActivityForResult(openAlbumIntent, PHOTOZOOM);
				}
			});
			cancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					popWindow.dismiss();

				}
			});
		}
		popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
		popWindow.setFocusable(true);
		popWindow.setOutsideTouchable(true);
		popWindow.setBackgroundDrawable(new BitmapDrawable());
		popWindow
				.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
	}

	private void updateAddressTv() {
		String address = "";
		if (!TextUtils.isEmpty(userInfo.province)) {
			address += db.selectOneCityDto(userInfo.province).region_name;
		}

		if (!TextUtils.isEmpty(userInfo.city)) {
			String c = db.selectOneCityDto(userInfo.city).region_name;
			if (!address.equals(c))
				address += "  " + c;
		}

		if (!TextUtils.isEmpty(userInfo.area)) {
			address += "  " + db.selectOneCityDto(userInfo.area).region_name;
		}

		if (!TextUtils.isEmpty(address)) {
			userAddressTv.setText(address);
		}
	}

	@Override
	public void refresh(Object... param) {
		try {
			int operType = (Integer) param[0];
			Object obj = param[1];
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			switch (operType) {

			case Task.EDIT_USER_SEX:
				if (obj != null) {
					UserDto dto = (UserDto) obj;
					if ("1".equals(dto.result)) {
						UserDto userInfo = getcurrentUser();
						userInfo.userSex = userSex;
						db.insertUserInfo(userInfo);
					} else
						LogUtil.e(dto.message);
				} else {
					LogUtil.e(getString(R.string.about_http_no_net_tip));
					// 重试 ?
				}
				break;

			case Task.EDIT_USER_CITY:
				if (obj != null) {
					UserDto dto = (UserDto) obj;
					if ("1".equals(dto.result)) {
						UserDto userInfo = getcurrentUser();
						userInfo.province = province;
						userInfo.city = city;
						userInfo.area = area;
						db.insertUserInfo(userInfo);
					} else
						LogUtil.e(dto.message);
				} else {
					LogUtil.e(getString(R.string.about_http_no_net_tip));
					// 重试 ?
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 注册广播
	 */
	public static final String COM_CHANGE_USER_CITY = "com.change.user.city";
	private BroadcastReceiver myReceiver;
	private String province, area, city;

	private void initRegisterReceiver() {
		myReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent i) {
				String action = i.getAction();
				if (action.equals(COM_CHANGE_USER_CITY)) {
					area = i.getStringExtra("area");
					city = db.selectOneCityDto(area).parent_id;
					province = db.selectOneCityDto(city).parent_id;

					String address = "";
					if (!TextUtils.isEmpty(province)) {
						address += db.selectOneCityDto(province).region_name;
					}

					if (!TextUtils.isEmpty(city)) {
						String c = db.selectOneCityDto(city).region_name;
						if (!address.equals(c))
							address += "  " + c;
					}

					if (!TextUtils.isEmpty(area)) {
						address += "  " + db.selectOneCityDto(area).region_name;
					}

					if (!TextUtils.isEmpty(address)) {
						userAddressTv.setText(address);
					}

					LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
					map.put("s", "account/edit_userinfo");
					map.put("device_code", AppUtils.getmDeviceID());
					map.put("token", "token");
					map.put("area",
							String.format("%s,%s,%s", province, city, area));
					getData(map, Task.EDIT_USER_CITY, 0);

				}
			}
		};

		IntentFilter i = new IntentFilter();
		i.addAction(COM_CHANGE_USER_CITY);
		registerReceiver(myReceiver, i);
	}

	private void unregisterReceiver() {
		unregisterReceiver(myReceiver);
	}

	@Override
	public void onDestroy() {
		if (userBmp != null) {
			userBmp.recycle();
		}
		unregisterReceiver();
		super.onDestroy();
	}

}
